package com.android.base.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;

import com.android.base.util.DisplayUtil;
import com.dq.util.R;
import com.dq.util.databinding.LibBaseDialogLoadingBinding;

/**
 * FileName: DialogLoading
 * Author: admin
 * Date: 2020/5/21 14:28
 * Description:
 */
public class DialogLoading extends Dialog {

    private final Activity activity;
    private LibBaseDialogLoadingBinding loadingBinding = null;
    private String content;
    private int duration = 0;

    public DialogLoading(@NonNull Activity context) {
        super(context, R.style.dialog_loading);
        this.activity = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        loadingBinding = LibBaseDialogLoadingBinding.inflate(activity.getLayoutInflater());
        setContentView(loadingBinding.getRoot());

        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = DisplayUtil.getScreenWidth(activity);
        lp.height = DisplayUtil.getScreenWidth(activity);
        getWindow().setAttributes(lp);

        setCanceledOnTouchOutside(false);
        setCancelable(false);

        initData();
    }

    private void initData() {
        if (TextUtils.isEmpty(content)) {
            loadingBinding.tvContent.setText("加载中...");
        } else {
            loadingBinding.tvContent.setText(content);
        }

        Animation rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.lib_base_anim_loading);
        LinearInterpolator lin = new LinearInterpolator();
        rotateAnimation.setInterpolator(lin);
        loadingBinding.imgIcon.startAnimation(rotateAnimation);

        if (duration != 0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    dismiss();
                }
            }, duration);
        }
    }

    public DialogLoading setContent(String c) {
        this.content = c;
        return this;
    }

    public DialogLoading setDuration(int d) {
        this.duration = d;
        return this;
    }

    @Override
    public void dismiss() {
        loadingBinding = null;
        super.dismiss();
    }
}